package org.hfy.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.hfy.dto.CustomerQueryDTO;
import org.hfy.entity.Customer;
import org.hfy.entity.Employee;
import org.hfy.mapper.CustomerMapper;
import org.hfy.service.CustomerService;
import org.hfy.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 客户Service实现类
 * 
 * @author hfy
 * @version 1.0
 */
@Service
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, Customer> implements CustomerService {

    @Autowired
    private EmployeeService employeeService;

    @Override
    public IPage<Customer> getCustomerPage(CustomerQueryDTO queryDTO) {
        Page<Customer> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
        return baseMapper.selectCustomerPage(page, queryDTO);
    }

    @Override
    public Customer getCustomerById(Long id) {
        return this.getById(id);
    }

    @Override
    public boolean addCustomer(Customer customer) {
        // 检查客户代码是否已存在
        if (checkCustomerCodeExists(customer.getCustomerCode(), null)) {
            throw new RuntimeException("客户代码已存在");
        }
        
        // 设置默认值
        if (StrUtil.isBlank(customer.getStatus())) {
            customer.setStatus("active");
        }
        
        customer.setCreatedAt(LocalDateTime.now());
        customer.setUpdatedAt(LocalDateTime.now());
        customer.setDeleted(false);
        
        return this.save(customer);
    }

    @Override
    public boolean updateCustomer(Customer customer) {
        // 检查客户代码是否已存在（排除当前记录）
        if (checkCustomerCodeExists(customer.getCustomerCode(), customer.getId())) {
            throw new RuntimeException("客户代码已存在");
        }
        
        customer.setUpdatedAt(LocalDateTime.now());
        return this.updateById(customer);
    }

    @Override
    public boolean deleteCustomer(Long id) {
        return this.removeById(id);
    }

    @Override
    public boolean checkCustomerCodeExists(String customerCode, Long excludeId) {
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customer_code", customerCode);
        if (excludeId != null) {
            queryWrapper.ne("id", excludeId);
        }
        return this.count(queryWrapper) > 0;
    }
    
    @Override
    public List<Map<String, Object>> getManagerList() {
        // 从员工表获取业务经理列表
        try {
            List<Employee> employees = employeeService.getAllEmployees();
            return employees.stream().map(employee -> {
                Map<String, Object> manager = new HashMap<>();
                manager.put("id", employee.getId());
                manager.put("name", employee.getEmployeeName());
                manager.put("employeeCode", employee.getEmployeeCode());
                return manager;
            }).collect(Collectors.toList());
        } catch (Exception e) {
            // 如果获取失败，返回空列表
            return new ArrayList<>();
        }
    }
    
    @Override
    public List<Customer> getAllCustomers() {
        QueryWrapper<Customer> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", false);
        queryWrapper.orderByAsc("customer_code");
        return this.list(queryWrapper);
    }
} 